<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="inet.db.tennis.TennisChampion"%>
<%@page import="inet.db.tennis.TennisMatch"%>
<%@page import="inet.util.DateTime"%>
<%@page import="inet.db.tennis.buffer.TennisBuffer"%>
<%@page import="inet.db.tennis.TennisPhase"%>
<%@page import="java.math.BigDecimal"%>
<%@page import="inet.db.tennis.TennisRound"%>
<%@page import="inet.db.tennis.TennisPlayer"%>
<jsp:useBean id="tennisChampionDAO" class="inet.db.tennis.TennisChampionDAO" scope="session"/>
<jsp:useBean id="tennisMatchDAO" class="inet.db.tennis.TennisMatchDAO" scope="session"/>
<jsp:useBean id="tennisPhaseDAO" class="inet.db.tennis.TennisPhaseDAO" scope="session"/>
<jsp:useBean id="tennisRoundDAO" class="inet.db.tennis.TennisRoundDAO" scope="session"/>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Danh sách trận đấu</title>
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/reset.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/text.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/grid.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/layout.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath() %>/admin/tennis/css/nav.css" media="screen" />
    <!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen" /><![endif]-->
    <!--[if IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen" /><![endif]-->
    <link href="<%= request.getContextPath() %>/admin/tennis/css/table/demo_page.css" rel="stylesheet" type="text/css" />
    <!-- BEGIN: load jquery -->
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="<%= request.getContextPath() %>/admin/tennis/text/javascript" src="js/jquery-ui/jquery.ui.core.min.js"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.widget.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.accordion.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.effects.core.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.effects.slide.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.mouse.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/jquery-ui/jquery.ui.sortable.min.js" type="text/javascript"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/table/jquery.dataTables.min.js" type="text/javascript"></script>
    <!-- END: load jquery -->
    <script type="text/javascript" src="<%= request.getContextPath() %>/admin/tennis/js/table/table.js"></script>
    <script src="<%= request.getContextPath() %>/admin/tennis/js/setup.js" type="text/javascript"></script>
    <script src="score.js"></script>
    <script src="status.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            setupLeftMenu();

            var oTable = $('.datatable').dataTable();
            oTable.fnSort( [ [1,'asc'] ] );
			setSidebarHeight();
        });
    </script>
    <script type="text/javascript">
    	function f_delete_select_item() {
    		document.formListMatch.action.value = 'delete_selected';
    		document.formListMatch.submit();
    	}
    	function f_delete_item(item_del) {
    		document.formListMatch.item_del.value = item_del; 
    		document.formListMatch.action.value = 'delete_item';
    		document.formListMatch.submit();
    	}
    	function update_item(item_up) {
    		document.formListMatch.item_up.value = item_up; 
    		document.formListMatch.action.value = 'update_item';
    		document.formListMatch.submit();
    	}
    </script>
</head>
<body>
 <%
	  request.setCharacterEncoding("utf-8");
	  response.setCharacterEncoding("utf-8");
   %>
    <div class="container_12">
        <%@ include file="../include/header.jsp" %>
        <% 
           String championCode = request.getParameter("championCode");
		   String sChampionCode = request.getParameter("slbChampion");
		   String sPhase = request.getParameter("slbPhase");
		   String sRound = request.getParameter("slbRound");
		   String sRoundCode = request.getParameter("slbChampion");
		   int roundNo = 0;
		   int sPhaseId = 0;
		   BigDecimal currPhase =null;
		   String currRound = "";
		   String sYear = request.getParameter("yearSelect");
		   String sMonth = request.getParameter("monthSelect");
		   String sDay = request.getParameter("daySelect");
		
		   DateTime dt = new DateTime();
		   if ((sYear == null)  || "".equals(sYear))  sYear = String.valueOf(dt.getYear());
		   if ((sMonth == null) || "".equals(sMonth)) sMonth = String.valueOf(dt.getMonth());
		   if (((sDay == null)  || "".equals(sDay)) && dt.getHour() < 11)   
		       sDay = String.valueOf(dt.getDay()-1);
		   else if(((sDay == null)  || "".equals(sDay)) && dt.getHour() >= 11)
		   	   sDay = String.valueOf(dt.getDay());	
		  
		   if (sPhase == null){
		   		 sPhaseId =0 ;
		   		 sPhase = "0";
		   }else{
		   		 sPhaseId =Integer.parseInt(sPhase) ;
		   }
		   if(championCode!=null){
			   		sChampionCode = championCode ;
			  
		   }
		  
		   if (sRound == null) sRound = "0";
		  		   
		   if ("0".equals(sYear))  sYear = null;
		   if ("0".equals(sMonth)) sMonth = null;
		   if ("0".equals(sDay))   sDay = null;
			//Vector<TennisMatch> vTennisMatch = tennisMatchDAO.findAll();
			TennisChampion championSelected = null;
			Vector<TennisChampion> tennisChampionVO = null;	
			if(sChampionCode != null) {
				championSelected = TennisBuffer.getChampionFromCode(sChampionCode);
				if(championSelected == null) {
					championSelected = TennisBuffer.reloadChampion(sChampionCode);
				}
				System.out.println("sChampionCode: "+sChampionCode);
				tennisChampionVO = tennisChampionDAO.getCurrentPhasedRound(sChampionCode);
				if(tennisChampionVO!=null){
					currPhase = tennisChampionVO.get(0).getCurrentPhase();
					if(currPhase!=null) sPhaseId=currPhase.intValue();
					currRound = tennisChampionVO.get(0).getCurrentRound();
					if(currRound!=null) sRound = currRound;
				}
			}
	
    		Vector<TennisRound> tennisRoundVO = null;	
			Vector<TennisMatch> vMatch = null;
			roundNo = tennisRoundDAO.getRoundNo(sPhaseId,sRound);
			
			//if("FIND".equals(sAction)) {
				//vMatch = tennisMatchDAO.findMatchList(sChampionCode, sRound, sDay, sMonth, sYear, orderByChampion);
				vMatch = tennisMatchDAO.findMatchListSchedule(sChampionCode,sRound,sPhaseId);
			//}
			Map<String, String> messages = new HashMap<String, String>();
			request.setAttribute("messages", messages); // Now it's available by ${messages}
			String bar = request.getParameter("bar");
			if(request.getParameter("ActionCreate")!=null){
			   tennisRoundVO = tennisRoundDAO.findTennisRoundNoAndChampionCode(sChampionCode,roundNo+1);
			  if(!sRound.equals("0")){
				  if(tennisRoundVO!=null && tennisRoundVO.size()>0 ){
				   		int x = 1;
						int y = 1;
						TennisMatch match = null;
						TennisMatch match2 = null;
						if(vMatch!=null && vMatch.size()>0){
							if(vMatch.size()%2 == 0){
								for(x=0; x < vMatch.size();x++ ) {
									int maxSTTInRound = 0;
									int maxSTTInRound2 = 0;
								  	y = x+1;
								    TennisMatch tenMatch = new TennisMatch();
								    TennisMatch tenMatch2 = new TennisMatch();
									match = vMatch.get(x);
									tenMatch.setChampionCode(tennisRoundVO.get(0).getChampionCode());
									tenMatch.setPhaseId(match.getPhaseId());
								  	tenMatch.setRound(tennisRoundVO.get(0).getRoundCode());
								   	maxSTTInRound = tennisMatchDAO.getMaxSTT(match.getPhaseId(), tennisRoundVO.get(0).getRoundCode());
								   	tenMatch.setStt(maxSTTInRound+1);
								   	
								   	match2 = vMatch.get(y);
									tenMatch2.setChampionCode(tennisRoundVO.get(0).getChampionCode());
								   	tenMatch2.setPhaseId(match2.getPhaseId());
								   	tenMatch2.setRound(tennisRoundVO.get(0).getRoundCode());
								   	maxSTTInRound2 = tennisMatchDAO.getMaxSTT(match2.getPhaseId(), tennisRoundVO.get(0).getRoundCode());								
								  	tenMatch2.setStt(maxSTTInRound2+1);
								   	BigDecimal id = tennisMatchDAO.insertRowTennisMatch(tenMatch);
								   	tennisMatchDAO.updateMapMatchId(match.getId(),id);	
								   	tennisMatchDAO.updateMapMatchId(match2.getId(),id);
								 	x= y;
						 		}
							 		sRoundCode =tennisRoundVO.get(0).getId().toString();
							 		 if(tennisRoundVO!=null){
										vMatch = tennisMatchDAO.findMatchListSchedule(sChampionCode,tennisRoundVO.get(0).getRoundCode(),sPhaseId );
										sRound = tennisRoundVO.get(0).getRoundCode();
									 }
							 		
					 		}else{
				   				messages.put("bar","Không thể tạo lịch đấu vì không đủ số cầu thủ!");
				   				vMatch = tennisMatchDAO.findMatchListSchedule(sChampionCode,sRound,sPhaseId);
				   			}
				   		
				 		}
				   }else{
				   		messages.put("bar","Chưa có vòng đấu tiếp theo!");
				   		vMatch = tennisMatchDAO.findMatchListSchedule(sChampionCode,sRound,sPhaseId);
				   }
			  }else{
				   		messages.put("bar","Chưa chọn vòng đấu!");
				   		vMatch = tennisMatchDAO.findMatchListSchedule(sChampionCode,sRound,sPhaseId);
				   }
			}
			String sAction = request.getParameter("action");
			TennisMatch matchVO = null;
			ArrayList err =null;
			boolean chk = false;
			// Delete selected rows
    	
    		if(request.getParameter("ActionUpdate")!=null) {
    			String[] listSTT = request.getParameterValues("stt");
    			String[] ids = request.getParameterValues("ids");
    			ArrayList arr = new ArrayList();
    			if(ids!=null){
					for(int i=0;i<listSTT.length;i++)
						for(int j =i+1;j<listSTT.length;j++){
							if(listSTT[i].equals(listSTT[j])){
								arr.add(i);
							}
					}
				}
				if(arr.size()>0){
					messages.put("bar","Số thứ tự không được trùng lặp!");
					vMatch = tennisMatchDAO.findMatchListSchedule(sChampionCode,sRound,sPhaseId);
				}else{
	    			for(int i =0;i<ids.length;i++){
	    				tennisMatchDAO.updateSTT(Integer.parseInt(ids[i]),Integer.parseInt(listSTT[i]));
	    			}
	    			vMatch = tennisMatchDAO.findMatchListSchedule(sChampionCode,sRound,sPhaseId);
    			}
    			
    		}
    		
        %>
        <div class="grid_10">
        <span style="text-align: center" class="error">${messages.bar}</span>
            <div class="box round first grid">
                <h2>Danh sách trận đấu</h2>
                <div class="block">
                	<form name="formListMatch" method="post">
                		<input name="action" type="hidden" />
                		<input name="item_del" type="hidden" />
                		<input name="item_up" type="hidden" value=""/>
                		<table class="form" style="text-align: center;">
                			<tr>
                				<td>
                					<a href="index.jsp">Giải đấu:</a>
                					<select id="select" name="slbChampion" >
                						<option value="0"> - Tất cả - </option>
                						<%
									        //Lay ten cac giai -CODE1
											 //Cache cac GIAI DAU tren bo nho, tranh truy cap DB nhieu lan.
										     Collection cChampions = TennisBuffer.getChampionList();
											 if (cChampions == null) {
												cChampions = tennisChampionDAO.findChampionRunning();
											 }
									         if (cChampions != null && cChampions.size() > 0) {
									             TennisChampion champion = null;
									             String selected = "";
									             int i=0;
									             for(Iterator it = cChampions.iterator(); it.hasNext();i++){
									                 champion = (TennisChampion)it.next();
									                 if (champion == null) continue;
									                 //Show current code
									                 if (champion.getCode().equals(sChampionCode)) {
									                     selected="selected";
									                 } else{
									                     selected="";
									                 }
									         %>
									         	 <%--Gia tri nhan duoc sau khi submit form la championCode --%>
									        	 <option value="<%=champion.getCode()%>" <%=selected%>> <%=champion.getName()%></option>
									         <%
									            } //for
									         }//if
										%>
                					</select>
                					<a href="#">Giai đoạn:</a>
                					<select id="select" name="slbPhase" >
                						<option value="0"> - Tất cả - </option>
                						<%
                						 if (championSelected != null) {
									         Collection cPhase = tennisPhaseDAO.findAll(championSelected.getCode(), championSelected.getCurrentSeason());
									         String selectedP = "";
									         TennisPhase phase = null;
									         
									         if(cPhase != null && !cPhase.isEmpty()) {
										         for(Iterator it = cPhase.iterator(); it.hasNext();) {
										             phase = (TennisPhase) it.next();
										             if (phase == null) continue;
										             if(phase.getId().toString().equals(sPhase)) {
										                 selectedP="selected";
										             } else {
										             	if(currPhase ==phase.getId()){
										             		 selectedP="selected";
										             	}else{
										                 	selectedP="";
										                 }
										             }
								        %>
								              <option value="<%=phase.getId()%>" <%=selectedP%>> <%=phase.getPhaseName()%></option>
								        <%
								          	 	}//for
								          	 }//if
								          }//if
								        %>
                					</select>
                					<a href="#">Vòng đấu:</a>
                					<select id="select" name="slbRound">
                						<option value="0"> - Tất cả - </option>
                						<%
                						System.out.println("currPhase: "+currPhase);
                						if(currRound!=null){
                							sPhase = currPhase.toString();
                						}
								         Collection cRounds = tennisRoundDAO.findAll(new BigDecimal(sPhase));
								         String selectedR = "";
								         TennisRound  round = null;
								         for(Iterator it = cRounds.iterator(); it.hasNext();) {
								             round = (TennisRound) it.next();
								              if (round == null) continue;
								              if(round.getRoundCode().equals(sRound)) {
								                  selectedR="selected";
								              } else {
								              	System.out.println("currPhase: "+currRound + " getRoundCode: "+round.getRoundCode());
								              		if(currRound.equals(round.getRoundCode())){
								              		 	selectedR="selected";
								              		}else{
								                  		selectedR="";
								                  	}
								              }
								        %>
								              <option value="<%=round.getRoundCode()%>" <%=selectedR%>> <%=round.getRoundCode()%></option>
								        <%
								          }//for
								        %>
                					</select>
     								<button type="button" onclick="document.formListMatch.action.value='FIND';document.formListMatch.submit();" class="btn btn-grey">Tìm kiếm</button>
                				</td>
                			</tr>
                		</table>
                		<p><button type="submit" name="ActionCreate" class="btn btn-grey">Tạo lịch thi đấu</button>
                		<button type="submit" name="ActionUpdate" class="btn btn-grey" style="margin-left: 577px;">Cập nhật số thứ tự trận đấu</button>
                		</p>
	                    <table class="data display datatable" id="example">
							<thead>
								<tr>
									<th style="width: 6%;">STT</th>
									<th style="width: 10%;">Mã giải</th>
									<th style="width: 13%;">Vòng</th>
									<th style="width: 14%;text-align: center;">Tay vợt 1</th>
									<th style="width: 14%;text-align: center;">Tay vợt 2</th>
									<th style="width: 1%;">Thứ tự trận đấu</th>
									<th style="width: 10%; " align="center">Giờ</th>
									<th style="width: 5%;">Sửa trận đấu</th>
								</tr>
							</thead>
							<tbody>
								<% 
									if(vMatch != null && !vMatch.isEmpty()) {
										TennisMatch match = null;
										int i = 0;
										TennisPlayer player1 = null;
										TennisPlayer player2 = null;
										DateTime matchDate = null;
										int stt = 0;
									for (Iterator it = vMatch.iterator(); it.hasNext(); i++) {
											match = (TennisMatch)it.next();
											if( match == null ) continue;
											if(match.getFirstPlayerId()!=null)
												player1 = (TennisPlayer) TennisBuffer.getPlayerFromId(match.getFirstPlayerId());
											if(match.getSecondPlayerId()!=null)
												player2 = (TennisPlayer) TennisBuffer.getPlayerFromId(match.getSecondPlayerId());
											stt =  match.getStt();
											if(match.getMatchDate()!=null)
												matchDate = new DateTime(match.getMatchDate());
										
								%>
								<tr >
									<td>
										<%= i+1 %>
									</td>
									<td><%= match.getChampionCodeSMS() %></td>
									<td><%= match.getRound() %></td>
									<td ><%= player1 != null ? player1.getName():"" %></td>									
									<td><%= player2 != null ? player2.getName():"" %></td>
									<td><input style="width: 100px" type="text"   name="stt" value = "<%= stt %>"></input></td>
									<td align="center">
									<%=(matchDate.getHour()+"h"+matchDate.getMinute()+"' ") +" "+ matchDate.getDay()+"/"+matchDate.getMonth()%>
									</td>	
									<td align="center"><a href="<%=request.getContextPath()%>/admin/tennis/match/edit-match.jsp?id=<%=match.getId() %>">
										<img alt="logo" src="<%=request.getContextPath()%>/admin/tennis/img/edit-icon.png" width="20" hight="12"/>
										</a>
									</td>
					
									<td><input name="ids" type="hidden" value="<%= match.getId() %>"/></td>
								</tr>
								<% 
										}// for
									} // if
								%>
							</tbody>
						</table>
					</form>
				<a href="add-match.jsp" class="btn-mini btn-black btn-plus" title="Thêm mới"><span></span>Add</a>
                </div>
            </div>
        </div>
        <div class="clear">
        </div>
    </div>
    <%@ include file="../include/footer.jsp" %>
</body>
</html>
